package com.hzqx.xxzx.framework.aspect;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import com.hzqx.xxzx.framework.annotation.SysLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;



import lombok.extern.slf4j.Slf4j;
@Component
@Aspect
@Slf4j
public class LogAspect {
	@Pointcut("@annotation(com.hzqx.xxzx.framework.annotation.SysLog)")
    public void pointcut() { }
	
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        // 保存日志
        log.info("程序执行时间:"+time/1000+"s");
        log.info(point+"");
        saveLog(point, time);
        return result;
    }
	 private void saveLog(ProceedingJoinPoint joinPoint, long time) {
	        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
	        Method method = signature.getMethod();
	        //SysLog sysLog = new SysLog();
	        SysLog logAnnotation = method.getAnnotation(SysLog.class);
	        if (logAnnotation != null) {
	            // 注解上的描述
	            log.info("注解上的描述"+logAnnotation.value());
	        }
	        // 请求的方法名
	        String className = joinPoint.getTarget().getClass().getName();
	        String methodName = signature.getName();
	        //sysLog.setMethod(className + "." + methodName + "()");
	        log.info("类名："+className);
	        log.info("方法名："+methodName);
	        // 请求的方法参数值
	        Object[] args = joinPoint.getArgs();
	        // 请求的方法参数名称
	        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
	        String[] paramNames = u.getParameterNames(method);
	        if (args != null && paramNames != null) {
	            String params = "";
	            for (int i = 0; i < args.length; i++) {
	                params += "  " + paramNames[i] + ": " + args[i];
	            }
	            log.info("参数名:"+params);
	        }
	        // 获取request
	        //HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
	        // 设置IP地址
	        //sysLog.setIp(IPUtils.getIpAddr(request));
	        // 模拟一个用户名
	        //sysLog.setUsername("mrbird");
	        //sysLog.setTime((int) time);
	        //sysLog.setCreateTime(new Date());
	        // 保存系统日志
	        //sysLogDao.saveSysLog(sysLog);
	    }
}
